<template>
  <div class="user-manage">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="queryParams.realName" placeholder="请输入真实姓名" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="userList">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="role.name" label="角色" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="400">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleSetRole(row)"
              v-if="row.username !== 'admin'"
            >设置角色</el-button>
            <el-button type="success" link @click="handleUpdatePassword(row)">修改密码</el-button>
            <el-button 
              type="primary"
              link
              @click="handleStatusChange(row)"
              :loading="row.statusLoading"
              :disabled="row.username === 'admin'"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              :disabled="row.username === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog
      :title="editDialog.title"
      v-model="editDialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitEdit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置角色对话框 -->
    <el-dialog :title="'设置角色 - ' + currentUser.username" v-model="roleDialogVisible" width="500px">
      <el-form :model="roleForm" ref="roleFormRef" label-width="80px">
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="roleForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRole">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      v-model="passwordDialog.visible"
      width="500px"
      @close="resetPasswordForm"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, updateUser, deleteUser, enableUser, disableUser, setUserRole, updateUserPassword } from '@/api/user'
import { getEnabledRoleList } from '@/api/role'

// 查询参数
const queryParams = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

// 用户列表数据
const loading = ref(false)
const userList = ref([])
const total = ref(0)

// 编辑对话框
const editDialog = reactive({
  visible: false,
  title: ''
})

// 编辑表单
const editFormRef = ref()
const editForm = reactive({
  id: undefined,
  username: '',
  realName: '',
  email: '',
  phone: '',
  status: undefined
})

// 角色设置
const roleDialogVisible = ref(false)
const currentUser = ref({})
const roleOptions = ref([])
const roleForm = reactive({
  roleId: undefined
})

// 表单校验规则
const editRules = {
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getUserList({
      ...queryParams
    })
    userList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRoles = async () => {
  try {
    const res = await getEnabledRoleList()
    roleOptions.value = res.data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.username = ''
  queryParams.realName = ''
  queryParams.email = ''
  queryParams.phone = ''
  queryParams.status = ''
  queryParams.pageNum = 1
  getList()
}

// 编辑用户
const handleEdit = (row) => {
  editDialog.visible = true
  editDialog.title = '编辑用户'
  editForm.id = row.id
  editForm.username = row.username
  editForm.realName = row.realName
  editForm.email = row.email
  editForm.phone = row.phone
  editForm.status = row.status
}

// 提交编辑
const submitEdit = async () => {
  await editFormRef.value.validate()
  try {
    await updateUser(editForm)
    ElMessage.success('修改成功')
    editDialog.visible = false
    getList()
  } catch (error) {
    console.error('修改用户失败:', error)
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该用户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  })
}

// 修改用户状态
const handleStatusChange = async (row) => {
  const text = row.status === 1 ? '禁用' : '启用'
  try {
    row.statusLoading = true
    if (row.status === 1) {
      await disableUser(row.id)
    } else {
      await enableUser(row.id)
    }
    row.status = row.status === 1 ? 0 : 1
    ElMessage.success(`${text}成功`)
  } catch (error) {
    console.error(`${text}用户失败:`, error)
  } finally {
    row.statusLoading = false
  }
}

// 打开设置角色对话框
const handleSetRole = (row) => {
  currentUser.value = row
  roleForm.roleId = row.roleId
  roleDialogVisible.value = true
}

// 提交角色设置
const submitRole = async () => {
  if (!roleForm.roleId) {
    ElMessage.warning('请选择角色')
    return
  }

  try {
    await setUserRole({
      userId: currentUser.value.id,
      roleId: roleForm.roleId
    })
    ElMessage.success('设置成功')
    roleDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('设置角色失败:', error)
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 修改密码相关数据
const passwordDialog = reactive({
  visible: false
})

const passwordForm = reactive({
  id: undefined,
  newPassword: ''
})

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' }
  ]
}

const passwordFormRef = ref()

// 打开修改密码对话框
const handleUpdatePassword = (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('不能修改管理员密码')
    return
  }
  passwordForm.id = row.id
  passwordDialog.visible = true
}

// 重置密码表单
const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  passwordForm.id = undefined
  passwordForm.newPassword = ''
}

// 提交密码表单
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateUserPassword(passwordForm)
        ElMessage.success('修改密码成功')
        passwordDialog.visible = false
        resetPasswordForm()
      } catch (error) {
        console.error('修改密码失败:', error)
      }
    }
  })
}

// 初始化
onMounted(() => {
  getList()
  getRoles()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 